<!DOCTYPE html>

<html>

<head>
<script type="text/javascript" src="jquery.js"></script>
<title>Upload to Flickr Options</title>

<script type="text/javascript">

var OptionsBackend = chrome.extension.getBackgroundPage().OptionsBackend;

function Options() {
  this.optionsMap = {};

  this.load = function(forceDefault) {
    this.optionsMap = OptionsBackend.load(forceDefault);
    var _this = this;
    $('input,select').each(function() {
      var $this = $(this);
      var name = $this.attr('name');
      if(name) {
        var converter = $this.attr('converter');
        if(converter) {
          Converters[converter].load($this, _this.optionsMap[name]);
        } else if($this.is('[type="checkbox"]')) {
          $this.attr('checked', _this.optionsMap[name]);
        } else if($this.is('[type="radio"]')) {
          if (_this.optionsMap[name] == $this.val()) {
            $this.attr('checked', true);
          }
        } else {
          $this.val(_this.optionsMap[name]);
        }
      }
    });
  };

  this.loadDefaults = function() {
    this.load(true);
    this.save();
  };

  this.save = function() {
    this.clearErrors();
    var hasErrors = false;
    var _this = this;
    $('input,select').each(function() {
      var $this = $(this);
      var validator = $this.attr('validator');
      if(validator) {
        var validatorsArray = validator.split(',');
        for(var i = 0; i < validatorsArray.length; ++i) {
          var validInfo = Validator[validatorsArray[i]]($this);
          if(validInfo !== true) {
            hasErrors = true;
            _this.addValidationError($this, validInfo);
            return true;
          }
        }
      }
    });
    var validInfo = Validator.global();
    if(validInfo !== true) {
      hasErrors = true;
      this.addValidationError(null, validInfo);
    }
    if(!hasErrors) {
      $('input,select,.color_selector').each(function() {
        var $this = $(this);
        var name = $this.attr('name');
        if(name) {
          var converter = $this.attr('converter');
          if(converter) {
            _this.optionsMap[name] = Converters[converter].save($this);
          } else if($this.is('[type="checkbox"]')) {
             _this.optionsMap[name] = $this.attr('checked');
          } else if($this.is('[type="radio"]')) {
             if($this.attr('checked')) {
                _this.optionsMap[name] = $this.val();
             }
          } else if($this.is('.color_selector')) {
            _this.optionsMap[name] = $this.attr('strColor');
          } else {
            var elValue = $this.val();
            var intValue = parseInt(elValue);
            if(intValue == elValue) {
              elValue = intValue;
            }
            _this.optionsMap[name] = elValue;
          }
        }
      });
      OptionsBackend.save(this.optionsMap);
      $(document).scrollTop(0);
      $("#saved_notice").stop().show().css('opacity', '1.0').fadeOut(5000);
    }
  };

  this.addValidationError = function($el, error) {
    var errorEl = $("<span>").attr('class', 'error').html(error);
    if($el) {
      $el.after(errorEl);
    } else {
      $("#buttons_area").before(errorEl);
    }
  };

  this.clearErrors = function() {
    $('.error').remove();
  };

}

/* ---- converters ---- */

Converters = {
  FadeoutTime: {
    load: function($el, val) {
      $el.val(val / 1000);
    },
    save: function($el) {
      return parseInt($el.val()) * 1000;
    }
  }
};

/* ---- validation ---- */
Validator = {
  global: function() {
    return true;
  },

  required: function ($el) {
    var val = $el.val()
    if(!val)
      return 'It can\'t be empty.';
    return true;
  },

  number: function ($el) {
    var intVal = parseInt($el.val());
    if(isNaN(intVal))
      return 'It should be a number.';
    return true;
  },

  positive: function ($el) {
    if(parseInt($el.val()) <= 0)
      return 'It should be positive.';
    return true;
  },

  url: function ($el) {
    if($el.val().match(/(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i)) {
      return true;
    }
    return 'It should be a valid URL.';
  }
}
/* ---- end validation ---- */

var options = new Options();

function toggleMode() {
	if ($("input[name='mode']:checked").val() == 'menu') {
		$("#hint_area").hide();
	} else {
		$("#hint_area").show();
	}
}

</script>

</head>
<body onload="options.load();toggleMode();">

<h1>Upload to Flickr Options</h1>

<div id="saved_notice" style="display:none">Your configuration has been successfully saved!</div>

<div id="mode_area">
  <fieldset>
    <legend>Mode:</legend>
    <label for="mode">Mode:</label>
    <input type="radio" name="mode" value="hint" onclick="toggleMode()"/> Hint on Image
    <input type="radio" name="mode" value="menu" onclick="toggleMode()"/> Context Menu
  </fieldset>
</div>

<div id="hint_area">
  <fieldset>
    <legend>Hint Icon:</legend>
    <label for="hint_icon">Hint icon:</label>
    <input type="radio" name="hint_icon" value="small" />Small icon:<img src="upload.small.png"/>
    <input type="radio" name="hint_icon" value="large" />Large icon:<img src="upload.large.png"/><br>
    <label for="hint_fadeout_time">Hint icon fade out time:</label>
    <input type="text" name="hint_fadeout_time" validator="required,number,positive" converter="FadeoutTime"/><br>
  </fieldset>

  <fieldset>
    <legend>Image Filters:</legend>
    <label for="min_img_width">Minimal image width:</label>
    <input type="text" name="min_img_width" validator="required,number,positive"/><br>
    <label for="min_img_height">Minimal image height:</label>
    <input type="text" name="min_img_height" validator="required,number,positive"/><br>
  </fieldset>
</div>
  <br>
<div id="buttons_area">
    <input type="button" value="Save" onclick="options.save();">
    <input type="button" value="Reset" onclick="options.load();toggleMode();">
    <input type="button" value="Reset to default" onclick="options.loadDefaults();toggleMode();">
</div>
</body>
</html>
